package com.phpxiu.app.view;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.phpxiu.app.config.HttpConfig;
import com.phpxiu.app.kkylive.KKYApp;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.model.event.OnTicketExchanged;
import com.phpxiu.app.model.event.WeiXinEvent;
import com.phpxiu.app.model.response.DrawRedModel;
import com.phpxiu.app.model.response.UserIncomeInfo;
import com.phpxiu.app.model.response.UserIncomeModel;
import com.phpxiu.app.okhttp.OKHttp;
import com.phpxiu.app.okhttp.OKHttpResponseModel;
import com.phpxiu.app.okhttp.handler.OKHttpUIHandler;
import com.phpxiu.app.okhttp.param.OKHttpParam;
import com.phpxiu.app.utils.KKYUtil;
import com.phpxiu.app.view.custom.WindowLayout;
import com.tencent.bugly.imsdk.crashreport.CrashReport;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;

import java.math.BigDecimal;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;

/**
 * 用户收益
 * Created by WuJinZhou on 2016/6/4.
 */
public class UserIncoming extends UIBase implements View.OnClickListener{
    public final static String TAG="UserIncoming";
    private WindowLayout mainView;
    private TextView ticketsView;//显示当前可用礼券数
    private long tickets=0;//当前可用礼券数，兑换成功会减少此数值
    private View operaView;
    private TextView balanceTv;//可领取红包
    private long money;//可领取红包RMB
    private int mRatio=1;
    private Button exchangeBtn;
    private Button bindToWXBtn;
    private OKHttpParam requestParam;
    private UserIncomeInfo mInfo;
    private boolean mBindWX=false;
    //微信
    private static IWXAPI WXApi;
    private boolean isRequestingWX=false;
    private boolean isDrawing=false;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        setContentView(R.layout.user_incoming);
        findViewById(R.id.top_bar_back_btn).setOnClickListener(this);
        findViewById(R.id.top_bar_draw_record_btn).setOnClickListener(this);
        WXApi= KKYApp.mWeiXinAPI;

        init();
    }

    /**
     * 初始化
     */
    private void init(){
        mainView=(WindowLayout)findViewById(R.id.root_view);
        ticketsView=(TextView)findViewById(R.id.dot_value);
        balanceTv=(TextView)findViewById(R.id.balance_value);
        operaView=findViewById(R.id.opera_box);
        exchangeBtn=(Button)findViewById(R.id.incoming_exchange_btn);
        bindToWXBtn=(Button)findViewById(R.id.incoming_bind_wx_btn);
        request();
    }

    /**
     * 请求界面数据
     */
    private void request(){
        if(requestParam==null){
            requestParam=OKHttpParam.builder(false);
        }
        OKHttp.post(HttpConfig.API_GET_EXCHANGE_INF, requestParam.jsonParam(), TAG, new OKHttpUIHandler(UserIncomeModel.class) {
            @Override
            public void onSuccess(Object model) {
                UserIncomeModel m = (UserIncomeModel) model;
                KKYUtil.log("我的收益数据："+m.getResponseStr());
                mInfo = m.getData();
                refreshView();
            }

            @Override
            public void onErr(String errMsg) {
                mainView.showTopMsg(errMsg);
            }
        });
    }

    public void refreshView(){
        if(mInfo==null){
            return;
        }
        try {
            tickets=Long.parseLong(mInfo.getVote());
        }catch (NumberFormatException e){
            e.printStackTrace();
        }
        ticketsView.setText(tickets+"");
        try {
            mRatio=Integer.parseInt(mInfo.getRatio());
        }catch (NumberFormatException e){
            mRatio=1;
            mainView.showTopMsg("ration is err");
            return;
        }
        money=tickets/mRatio;
        //BigDecimal value =new BigDecimal(money);
        //money=value.setScale(2,BigDecimal.ROUND_HALF_UP).floatValue();
        balanceTv.setText(money+"");
        mBindWX=("1".equals(mInfo.getBind()));
        if(mBindWX){
            KKYUtil.log("我的收益数据:已绑定过微信");
            bindToWXBtn.setText(getString(R.string.ui_income_money_label));
        }else{
            KKYUtil.log("我的收益数据:未绑定过微信");
            bindToWXBtn.setText(getString(R.string.ui_income_bind_label));
        }
        operaView.setVisibility(View.VISIBLE);
        exchangeBtn.setOnClickListener(this);
        bindToWXBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.top_bar_back_btn:
                onBackPressed();
                break;
            case R.id.top_bar_draw_record_btn:
                records();
                break;
            case R.id.incoming_exchange_btn:
                exchange();
                break;
            case R.id.incoming_bind_wx_btn:
                bindToWX();
                break;
            default:
                break;
        }
    }

    /**
     *查看领取记录
     */
    private void records(){
        Intent record=new Intent(this,DrawRecord.class);
        startActivity(record);
    }

    /**
     * 兑换
     * 1.利用收入的票兑换钻石
     */
    private void exchange(){
        try {
            Intent exchange=new Intent(this,Exchange.class);
            exchange.putExtra(Exchange.TICKETS_KEY,tickets);
            startActivity(exchange);
        }catch (NumberFormatException e){
            CrashReport.postCatchedException(e);
        }

    }

    /**
     *绑定到微信
     */
    private void bindToWX(){
        if(mBindWX){
            if(isDrawing){
                return;
            }
            //直播调用领取接口
            drawRedPackage();
        }else{
            if(isRequestingWX){
                return;
            }
            //绑定微信
            if(!WXApi.isWXAppInstalled()){
                mainView.showTopMsg(getString(R.string.login_wechat_not_install));
                return;
            }
            isRequestingWX=true;
            final SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = System.currentTimeMillis()+"";//传随机数
            WXApi.sendReq(req);
        }
    }

    /**
     * 微信登录
     */
    @Subscribe
    public void onWeiXinLogin(WeiXinEvent event){
        if(event.getCode()==WeiXinEvent.LOGIN_SUCCESS) {
            requestBindWX(event.getUnionId());
            return;
        }
        if(event.getCode()==WeiXinEvent.LOGIN_ERR) {
            mainView.showTopMsg(getString(R.string.login_failed));
        }
        isRequestingWX=false;
    }

    /**
     * 请求绑定微信
     */
    final private void requestBindWX(final String unionId){
        if(unionId==null||"".equals(unionId)){
            mainView.showTopMsg("The unionId is invalid");
            return;
        }
        OKHttpParam param=OKHttpParam.builder(false);
        param.put("unionid",unionId);
        OKHttp.post(HttpConfig.API_BIND_WX, param.jsonParam(), TAG, new OKHttpUIHandler(OKHttpResponseModel.class) {
            @Override
            public void onSuccess(Object model) {
                mBindWX = true;
                bindToWXBtn.setText(getString(R.string.ui_income_money_label));
                isRequestingWX=false;
            }

            @Override
            public void onErr(String errMsg) {
                mainView.showTopMsg(errMsg);
                isRequestingWX=false;
            }
        });
    }

    /**
     * 领取红包
     */
    final private void drawRedPackage(){
        if(money==0){
            mainView.showTopMsg(getString(R.string.ui_income_balance_not_enough));
            return;
        }
        isDrawing=true;
        OKHttpParam param=OKHttpParam.builder(false);
        OKHttp.post(HttpConfig.API_DRAW_RED_PACKAGE,param.jsonParam(),TAG,new OKHttpUIHandler(DrawRedModel.class) {
            @Override
            public void onSuccess(Object model) {
                isDrawing=false;
                DrawRedModel m=(DrawRedModel)model;
                try {
                    tickets=Long.parseLong(m.getData().getVote());
                    //ticketsView.setText(tickets+"");
                    //money=tickets/mRatio;
                    //BigDecimal value =new BigDecimal(money);
                    //money=value.setScale(2,BigDecimal.ROUND_HALF_UP).floatValue();
                    balanceTv.setText(money+"");
                    EventBus.getDefault().post(new OnTicketExchanged(true,tickets));//通知用户中心刷新票数
                }catch (NumberFormatException e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onCodeErr(String code, String msg) {
                isDrawing=false;
                if("21005".equals(code)){
                    if(mInfo==null){
                        return;
                    }
                    alert(getString(R.string.code_21005)+mInfo.getWechat_public(),null);
                }else{
                    mainView.showTopMsg(msg);
                }
            }

            @Override
            public void onErr(String errMsg) {
                isDrawing=false;
            }
        });

    }

    /**
     * 兑换更新票数
     */
    @Subscribe
    public void OnVoteExchange(OnTicketExchanged event){
        if(mInfo!=null){
            if(event.isTotal()){
                tickets=event.getVote();
            }else{
                tickets=tickets-event.getVote();
            }

            if(tickets<0){
                tickets=0;
            }
            mInfo.setVote(tickets + "");
            //ticketsView.setText(tickets+"");
            if(mRatio==0){
                return;
            }
            money=tickets/mRatio;
            //BigDecimal value =new BigDecimal(money);
            //money=value.setScale(2,BigDecimal.ROUND_HALF_UP).floatValue();
            handler.post(new Runnable() {
                @Override
                public void run() {
                    balanceTv.setText(money+"");
                    ticketsView.setText(tickets + "");
                }
            });
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
